package chpt12.dao;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;

public class StudentApp extends JFrame {
	private JTextField txtInput;
	private JButton btQuery;
	private JTable table;
	private DefaultTableModel tModel;
	private StudentModel studentModel;

	public StudentApp() {
		studentModel = new StudentModel();
		this.setLayout(new BorderLayout()); // 使用BorderLayout布局管理器

		// 添加顶部面板
		JPanel topPanel = new JPanel();
		topPanel.add(new JLabel("姓名："));
		txtInput = new JTextField(20);
		topPanel.add(txtInput);
		btQuery = new JButton("查询");
		btQuery.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				String name = txtInput.getText().trim();
				if (name.equals(""))
					studentModel.queryStudentAll();
				else
					studentModel.queryStudentByName(name);
				tModel.setDataVector(studentModel.getTableData(), 
						studentModel.getTableHead()); //刷新表格数据
			}
		});
		topPanel.add(btQuery);
		this.add(topPanel, BorderLayout.NORTH);

		// 添加中间面板
		tModel = new DefaultTableModel(studentModel.getTableData(), 
				studentModel.getTableHead());
		table = new JTable(tModel);
		JScrollPane scrollPane = new JScrollPane(table);
		this.add(scrollPane, BorderLayout.CENTER);

		// 添加底部面板
		JPanel bottomPanel = new JPanel();
		bottomPanel.add(new JLabel("其他信息"));
		JButton btDelete = new JButton("删除");
		btDelete.addActionListener(new ActionListener() {
		    @Override
		    public void actionPerformed(ActionEvent e) {
		        int selectedRow = table.getSelectedRow();
		        if (selectedRow != -1) {
		        	String x = (String) tModel.getValueAt(selectedRow, 0); 
		            Long id = Long.parseLong(x); 
		            studentModel.deleteStudentById(id);
		            tModel.removeRow(selectedRow);
		        }
		    }
		});
		bottomPanel.add(btDelete);
		// 添加更多组件...
		this.add(bottomPanel, BorderLayout.SOUTH);

		this.setBounds(200, 350, 350, 240);
		this.setTitle("学生信息查询");
		this.setVisible(true);
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
		this.addWindowListener(new WindowAdapter() {
			public void windowClosed(WindowEvent e) {
				JDBCUtil.closeAll(null, null, null);
			}
		});
	}

	public static void main(String[] args) {
		// 在Event Dispatch Thread中创建和显示GUI
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				new StudentApp();
			}
		});
	}
}